package com.capgemini;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ChuckNorrisDao implements Serializable{

	private static long serialVersionUID = -5935858088136090056L;
	
	@PersistenceContext
	EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	public Map<Long, ChuckNorrisFact> getFacts() {
		List<ChuckNorrisFact> list = entityManager.createQuery("from ChuckNorrisFact").getResultList();
		
		System.out.println(list.toArray());
		
		Map<Long, ChuckNorrisFact> _facts = new HashMap<Long, ChuckNorrisFact>();
		
		for (ChuckNorrisFact chuckNorrisFact : list) {
			System.out.println(chuckNorrisFact);
			
			_facts.put(chuckNorrisFact.getId(), chuckNorrisFact);
		}
		
		
		return _facts;
	}
	
	public ChuckNorrisFact getFactById(Long id) {
		try {
			return entityManager.find(ChuckNorrisFact.class, id);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			
		}
		
		return null;
	}

	public void addFact(ChuckNorrisFact f) {
		entityManager.persist(f);
		entityManager.flush();
	}

	public ChuckNorrisFact getRandomFact() {
		Random randomGenerator = new Random();
		
		
		Map<Long, ChuckNorrisFact> f = getFacts();
		int r = randomGenerator.nextInt(f.size());
		System.out.println("Random number : " + r);
		Collection<ChuckNorrisFact> c = f.values();
		Object[] array = c.toArray();
		
		System.out.println(array);
		return (ChuckNorrisFact) array[r];
	}

	@Override
	public String toString() {
		return null;
	}


	
	
}

















//public void addFact(ChuckNorrisFact f) {
//	entityManager.persist(f);
//	entityManager.flush();
//	
//}